/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package job;

import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 *
 * @author Andrea
 */
public class JobsManager implements Observer {

    private static final JobsManager INSTANCE;

    private static List<Worker> wconn;

    static {
        INSTANCE = new JobsManager();
    }

    private JobsManager() {
        wconn = new ArrayList<>(20);
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Worker) {
            wconn.remove((Worker) o);
        } else {
            throw new IllegalArgumentException("you must be a Worker to be register to the JobsManager");
        }
    }

    public static void addWorkers(Worker... w) {
        wconn.addAll(Arrays.asList(w));

        for (Worker w1 : w) {
            w1.logToManager(INSTANCE);
        }
    }
    
    public static void notifyReady(Worker w){
        throw new UnsupportedOperationException("not implemented yet");
    }

    private static URL getClassLocation(Class clazz) {
        if (clazz == null) {
            return null;
        }
        try {
            ProtectionDomain protectionDomain = clazz.getProtectionDomain();
            CodeSource codeSource = protectionDomain.getCodeSource();
            URL location = codeSource.getLocation();

            return location;
        } catch (Throwable e) {
            return null;
        }
    }
    
    public static File getJarLocation(Work w){
        
        URL url = getClassLocation(w.getClass());
        
        if(url == null){
            return null;
        }
        
        return new File(url.getFile());
    }
    
    public static File getJarLocation(Class clazz){
        
        URL url = getClassLocation(clazz);
        
        if(url == null){
            return null;
        }
        
        return new File(url.getFile());
    }
}
